<template>
  <div class="filter-containter m-flex-col m-flex-col--top">
    <div class="filter-header"></div>
    <div class="filter-block">
      <!--筛选项——仓库-->
      <filter-item itemName="仓库">
        <t-select
          v-model="projectId"
          filterable
          placeholder="搜索仓库"
          :onSearch="remoteProjectMethod"
          :loading="projectSearchLoading"
          :options="projectList"
          @change="watchProjectId">
        </t-select>
      </filter-item>
      <!--筛选项——分支, 叫ref-->
      <filter-item itemName="分支">
        <t-select
          :disabled="projectId === ''"
          v-model="branchId"
          :options="branchList"
          @change="changeBranchName"
          placeholder="默认master分支（单选）">
        </t-select>
      </filter-item>
      <!--筛选项——筛选类型-->
      <!--<filter-item itemName="筛选类型">-->
      <!--  <t-select-->
      <!--    v-model="scopeType"-->
      <!--    :options="scopeList"-->
      <!--    placeholder="默认筛选项为blobs"-->
      <!--    clearable>-->
      <!--  </t-select>-->
      <!--</filter-item>-->
      <!--搜索范围-->
      <!--<filter-item itemName="搜索范围(指定搜索目录)">-->
      <!--  <t-tree-->
      <!--    :data="catalogueList"-->
      <!--    hover-->
      <!--    expand-all-->
      <!--    line-->
      <!--    checkable-->
      <!--    v-model="activedCatalog"-->
      <!--    :load="load"-->
      <!--    :icon="icon">-->
      <!--  </t-tree>-->
      <!--</filter-item>-->
    </div>
  </div>
</template>

<script>
import { Icon } from "tdesign-icons-vue";
import FilterItem from "@/components/FilterItem";
import { mapMutations, mapGetters } from "vuex";
export default {
  name: "FilterMenu",
  components: { FilterItem },
  data() {
    return {
      projectSearchLoading: false, // loading状态

      // 筛选类型
      scopeList: [
        {
          label: "blobs(项目文件内容)",
          value: "blobs",
        },
        {
          label: "代码提交",
          value: "commits",
        },
        {
          label: "代码合并请求",
          value: "merge_requests",
        },
      ],

      // 搜索范围
      catalogueList: [],
      activedCatalog: [],
    };
  },
  computed: {
    ...mapGetters([
      "storeGetterScopeType",
      "storeGetterProjectId",
      "storeGetterBranchId",
      "storeGetterProjectList",
      "storeGetterBranchList",
    ]),
    projectId: {
      get() {
        return this.storeGetterProjectId;
      },
      set(val) {
        this.changeProjectId(val);
      },
    },
    scopeType: {
      get() {
        return this.storeGetterScopeType;
      },
      set(val) {
        this.changeScopeType(val);
      },
    },
    branchId: {
      get() {
        return this.storeGetterBranchId;
      },
      set(val) {
        this.changeBranchId(val);
      },
    },
    projectList: {
      get() {
        return this.storeGetterProjectList;
      },
      set(val) {
        this.changeProjectList(val);
      },
    },
    branchList: {
      get() {
        return this.storeGetterBranchList;
      },
      set(val) {
        this.changeBranchList(val);
      },
    },
  },
  methods: {
    ...mapMutations([
      "changeScopeType",
      "changeProjectId",
      "changeBranchId",
      "changeProjectList",
      "changeBranchList",
    ]),
    async changeBranchName(e) {
      console.log("changeBranchName --> ", e);
      let allCataLog = await this.getProjectAllCatalog();
      this.catalogueList = allCataLog;
    },
    // 搜索仓库
    remoteProjectMethod(search) {
      this.projectSearchLoading = true;
      // 模糊搜索项目
      this.$Api.Search.all("projects", search)
        .then((projects) => {
          this.projectSearchLoading = false;
          if (projects?.length >= 0) {
            let projectList = [];
            for (const projectItem of projects) {
              projectList.push({
                value: projectItem.id || "",
                label: projectItem.name || "",
                ...projectItem,
              });
            }
            this.projectList = projectList;
          } else {
            this.projectList = [];
            this.changeProjectId("");
          }
        })
        .catch((err) => {
          this.projectSearchLoading = false;
          console.error("err --> ", err);
        });
    },
    // 监听到搜索到仓库变化，重新请求对应的仓库下信息
    async watchProjectId() {
      // 清空默认
      this.changeBranchId("master");
      this.branchList = [];
      // 搜索仓库对应的所有分支
      await this.getProjectAllBranch();
      // 这个初始化的时候搜索仓库下的一级目录树
      let allCataLog = await this.getProjectAllCatalog();
      this.catalogueList = allCataLog;
    },
    // 搜索仓库对应的所有分支
    getProjectAllBranch() {
      const that = this;
      //根据项目ID，查询项目的所有分支
      return this.$Api.Branches.all(this.projectId)
        .then((branches) => {
          if (branches?.length >= 0) {
            branches.forEach((element, index) => {
              element.name === "master" && this.changeBranchId(index);
              that.branchList.push({
                label: element?.name,
                value: index,
                ...element,
              });
            });
          } else {
            this.branchList = [];
            this.changeBranchId("master");
          }
        })
        .catch((res) => {
          console.error("res --> ", res);
        });
    },

    /**
     * 搜索仓库下的目录树
     * @param {*} isRecursive 是否递归搜索结果
     * @param {*} path 指定目录下搜索
     */
    getProjectAllCatalog(isRecursive = false, path = "") {
      const ref =
        this.branchList?.filter((item) => {
          return item?.value == this.branchId;
        })[0]?.label || "master";
      return this.$Api.Repositories.tree(this.projectId, {
        ref,
        path: path,
        recursive: isRecursive,
      })
        .then((res) => {
          // 过滤下目录类型的进行展示
          let catalogListArr = [];
          for (let i = 0; i < res?.length; i++) {
            if (res[i]?.type === "tree") {
              catalogListArr.push({
                label: res[i]?.name,
                children: true,
                ...res[i],
              });
            }
          }
          return catalogListArr;
        })
        .catch((err) => {
          console.error("err --> ", err);
          return [];
        });
    },
    // 动态设置 搜索范围树的icon样式
    icon(createElement, node) {
      let name = "file";
      if (node.getChildren()) {
        if (node.expanded) {
          name = "folder-open";
          if (node.loading) {
            name = "loading";
          }
        } else {
          name = "folder";
        }
      }
      return <Icon name={name} />;
    },
    load(node) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        // 加载指定目录下的子目录
        let res = await this.getProjectAllCatalog(false, node?.data?.path);
        if (!res?.length || res?.length <= 0) {
          resolve([]);
        }
        resolve(res);
      });
    },
  },
};
</script>

<style lang="scss">
.filter-containter {
  width: 100%;
  height: 100vh;
  padding: 20px 10px;
  .filter-block {
    width: 100%;
  }
}
</style>
